#!/usr/bin/python2.7
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

'''
Created on 5 December 2011

@author: ibrahimelfar@google.com (Ibrahim El Far)
'''

from itertools import product
from django.template import Context, Template

class Template:
    '''
    Description
    
    Attributes:
        language
        context
        name
        content
    '''

    def __init__(self, language, context, name, content):
        '''
        Description
            
        Args:
            language
            context
            name
            content
        '''
        self.language = language
        self.context = context
        self.name = name
        self.content = content

class EclipseTemplateSerializer:
    SINGLE = Template('<template autoinsert="true" context="{{context}}" deleted="false" description="" enabled="true" name="{{name}}">{{content}}</template>') 
    MULTIPLE = '''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <templates>
        {% for template in templates %}
        
        {% endfor %}
    </templates>'''
    def serialize_many(self, infos):
        serializations = ['<?xml version="1.0" encoding="UTF-8" standalone="no"?><templates>']
        for info in infos:
            serializations.append(self.serialize_one(info))
        serializations.append('</templates>')
        return ''.join(serializations)

    def serialize_one(self, info):
        return self.SERIALIZATION_TEMPLATE.render(Context(vars(info)))

print EclipseTemplateSerializer().serialize_one(Template('html', 'html_all', 'name', 'content'))

#def generate(eclipse_contexts, eclipse_template_name, utterance, eclipse_template,
#             *arguments, **keywords):
#    eclipse_templates = []
#    
#    keys = keywords.keys()
#    keyword_count = len(keys)
#
#    if (keyword_count == 0):
#        for eclipse_context in eclipse_contexts:
#            eclipse_templates.append(Template(eclipse_context,
#                                                     eclipse_template_name,
#                                                     utterance,
#                                                     eclipse_template))
#        return eclipse_templates
#
#    lists = []
#    for key in keys:
#        lists.append(keywords[key])
#    rendering_context = {}
#    for combination in product(*lists):
#        for i in range(keyword_count):
#            rendering_context[keys[i][:-1]] = combination[i]
#        rendered_eclipse_template_name = Template(eclipse_template_name).render(Context(rendering_context))
#        rendered_utterance = Template(utterance).render(Context(rendering_context))
#        rendered_eclipse_template = Template(eclipse_template).render(Context(rendering_context))
#        for eclipse_context in eclipse_contexts:
#            eclipse_templates.append(Template(eclipse_context,
#                                                     rendered_eclipse_template_name,
#                                                     rendered_utterance,
#                                                     rendered_eclipse_template))
#    
##        for eclipse_context in eclipse_contexts:
##            eclipse_templates.append((eclipse_context, eclipse_template_name, eclipse_template))
#    return eclipse_templates

#class Html:
#    contexts = ['html_all']
#    one_line_tags = []
#    multi_line_tags = []
#    one_line_attribute_ready_tags = []
#    multi_line_attribute_ready_tags = []
#    
#    def generate(self):
#        pass
#
#for t in generate(eclipse_contexts=['html_all'],
#                  eclipse_template_name='{{tag}}-tag-eclipse-listen',
#                  utterance = '{{tag}} tag',
#                  eclipse_template='<{{tag}}>${cursor}</{{tag}}>',
#                  tags=['html', 'body', 'head'],
#                  ):
#    print serialize_eclipse_template(t)
#
## all by utterance (implicitly add tag), implicity hyphenate and add prefix to get template name.

class Html:
    class Meta:
        languages = ['html']
        contexts = ['html_all']
        
    class Pattern:
        utterances = {}
        
        def name(self):
            if not self.utterances.has_key('en-us'):
                return ''
            if len(self.utterances['en-us']) == 0:
                return ''

            name_template = Template(''.join([self.utterances['en-us'][0].replace(' ', '-'), '-eclipse-listen']))
            return name_template.render(Context(locals()))

    class TagPattern(Pattern):
        utterances = {'en-us': ['create {{tag}}',
                                'new {{tag}}',
                                '{{tag}} tag'
                                ]
                      }

    class TagOnSelectionPattern(Pattern):
        utterances = {'en-us': ['{{tag}} that',
                                'mark {{tag}}',
                                'mark as {{tag}}'
                                ]
                      }

    class MultipleLineTagPattern(TagPattern):
        template = '''<{{tag}}>
            ${cursor}
        </{{tag}}>
        '''

    class MultipleLineTagOnSelectionPattern(TagPattern):
        template = '''<{{tag}}>
            ${text}
        </{{tag}}>
        ${cursor}
        '''
        
print Html.MultipleLineTagPattern().name()

class Utterances:
    create_tag = {'en-us': ['create tag', 'new tag']}

class EclipseTemplateGenerator:
    class Meta:
        language = 'html'
        context = 'html_all'
        utterance_affixes = (['', 'create'], [' tag'])
        utterance_affixes_selection = (['mark ', 'mark as'], ['', 'tag'])

    class MultipleLinePattern:
        utterance = '{{prefix}}{{tag}}{{suffix}}'
        template = ''
        index = 2
        
        class Variables:
            tag = []
            suffix = []
            prefix = []
        
    create_tag = dict(content='<{{tag}}>${cursor}</{{tag}}>')
    
    multi_line = dict(name='')

{'en-us': ['create attribute', 'new attribute']}

# Multiple Line (with tag + that flavors)
# <address>
# <article>
# <aside>
#<body>
#<details>

# Multiple line (tag + that + id attribute)
#<canvas>
#<datalist>
#<div>



# Single Line (with tag + that flavors)
# <b>
#<bdi> (bidirectional isolation)
#<caption>
#<cite>
#<code>


# Not supported in HTML5
# <acronym>
# <applet>
#<basefont>
#<big>
#<center>
#<dir>


# <!-->
'comment', '<!-- ${cursor} -->'
# <!DOCTYPE>
'document type', '<!DOCTYPE ${html}>${cursor}'
# <a>
'hyperlink', '<a href="${url}">${text}</a>${cursor}'
'hyperlink that', '<a href="${url}">${word_selection}</a>${cursor}'
# <abbr>
'abbreviation', '<abbr title="World Health Organization">${abbreviation}</abbr>'
'abbreviate that', '<abbr title="World Health Organization">${word_selection}</abbr>'
# <area>
'area', '<area shape="${shape}" coords="${x1},${y1},${x2},${y2}" href="${url}" alt="${alt_text}" />'

# <audio>
'audio', '''<audio controls="${controls}">
  <source src="${file}.ogg" type="audio/ogg" />
  <source src="${file}.mp3" type="audio/mp3" />
  Your browser does not support the audio tag.
</audio>'''

# <base>
'base', '<base href="${url}" target="${target}" />'

#<bdo> (bidirectional override)
'bdo', '''<bdo dir="rtl">
This text will go right-to-left.
</bdo>'''

#<blockquote>
'block quote', '''<blockquote cite="${url}">
${quote}
</blockquote>'''


#<br>
'line break', '<br/>'

#<button>
'button', '<button type="button">Click Me!</button>'
'button that'
'full button'

# table stuff
#<col>
#<colgroup>

#<command>
'', '<command type="command" label="Save" onclick="save()">Save</command>'

# definition list stuff
#<dd>
#<dl>
#<dt>

# mark deleted / mark inserted
#<del>


#<em>    Renders as emphasized text
#<strong>    Defines important text
#<dfn>    Defines a definition term
#<code>    Defines a piece of computer code
#<samp>    Defines sample output from a computer program
#<kbd>    Defines keyboard input
#<var>    Defines a variable



#<embed>
#<fieldset>
#<figcaption>
#<figure>
#<font>
#<footer>
#<form>
#<frame>
#<frameset>
#<h1> - <h6>
#<head>
#<header>
#<hgroup>
#<hr>
#<html>
#<i>
#<iframe>
#<img>
#<input>
#<ins>
#<keygen>
#<kbd>
#<label>
#<legend>
#<li>
#<link>
#<map>
#<mark>
#<menu>
#<meta>
#<meter>
#<nav>
#<noframes>
#<noscript>
#<object>
#<ol>
#<optgroup>
#<option>
#<output>
#<p>
#<param>
#<pre>
#<progress>
#<q>
#<rp>
#<rt>
#<ruby>
#<s>
#<samp>
#<script>
#<section>
#<select>
#<small>
#<source>
#<span>
#<strike>
#<strong>
#<style>
#<sub>
#<summary>
#<sup>
#<table>
#<tbody>
#<td>
#<textarea>
#<tfoot>
#<th>
#<thead>
#<time>
#<title>
#<tr>
#<track>
#<tt>
#<u>
#<ul>
#<var>
#<video>
#<wbr>

